package com.ywjt.pinkelephant.home.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ywjt.pinkelephant.widget.WindowsManagerPicker;
import com.ywjt.pinkelephant.R;
import com.ywjt.pinkelephant.base.BaseActivity;
import com.ywjt.pinkelephant.home.adapter.CircleColorsAdapter;
import com.ywjt.pinkelephant.util.SPUtils;
import com.ywjt.pinkelephant.widget.RoundRelativeLayout;
import com.ywjt.pinkelephant.widget.SwitchButton;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class ActivityPopuSet extends BaseActivity implements View.OnClickListener {
    private RecyclerView rcColor;
    private CircleColorsAdapter colorsAdapter;
    private List<String> colors;
    private NestedScrollView nsview;
    private SeekBar sbSize,sbVideoSpeed,sbTransparent;
    private TextView tvSize,tvSpeed;
    private RoundRelativeLayout rlMid;
    private TextView tvCountDown,tvStart;
    private MyHandler myHandler=null;

    private TextView tvTextColor,tvBackColor,tvText,tvTransparent;
    private SwitchButton sbLocationLine;
    private TextView  tvRate1,tvRate4,tvRate3,tvRate16,tvRate9;
    private int color=0;//0字体颜色 1 背景颜色


    private AlertDialog mOpenPermission;
    private static final int REQUEST_CODES = 100;

    public static void actionStart(Context context ) {
        Intent intent = new Intent(context, ActivityPopuSet.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvTextColor:
                color=0;
                tvTextColor.setBackgroundResource(R.drawable.purple_12);
                tvBackColor.setBackgroundResource(0);
                break;
            case R.id.tvBackColor:
                color=1;
                tvTextColor.setBackgroundResource(0);
                tvBackColor.setBackgroundResource(R.drawable.purple_12);
                break;
            case R.id.tvStart:
                //开始提词
                tvCountDown.setVisibility(View.VISIBLE);
                startCountTime();
                break;
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_popuset;
    }

    @Override
    protected void initView() {
        setTitleText("悬浮窗设置");
        rcColor=findViewById(R.id.rcColor);
        nsview=findViewById(R.id.nsview);
        tvSize=findViewById(R.id.tvSize);
        tvSpeed=findViewById(R.id.tvSpeed);
        tvRate1=findViewById(R.id.tvRate1);
        sbVideoSpeed=findViewById(R.id.sbVideoSpeed);
        tvBackColor=findViewById(R.id.tvBackColor);
        sbLocationLine=findViewById(R.id.sbLocationLine);
        tvTransparent=findViewById(R.id.tvTransparent);
        rlMid=findViewById(R.id.rlMid);
        tvText=findViewById(R.id.tvText);
        tvStart=findViewById(R.id.tvStart);
        tvCountDown=findViewById(R.id.tvCountDown);
        sbTransparent=findViewById(R.id.sbTransparent);
        tvTextColor=findViewById(R.id.tvTextColor);
        sbSize=findViewById(R.id.sbSize);
        tvRate4=findViewById(R.id.tvRate4);
        tvRate3=findViewById(R.id.tvRate3);
        tvRate16=findViewById(R.id.tvRate16);
        tvRate9=findViewById(R.id.tvRate9);
        tvRate9.setOnClickListener(this::onClick);
        tvRate16.setOnClickListener(this::onClick);
        tvRate3.setOnClickListener(this::onClick);
        tvRate4.setOnClickListener(this::onClick);
        tvRate1.setOnClickListener(this::onClick);

        rlMid.setRadius(17);

        colors=new ArrayList<>();
        colors.add("ff0000");
        colors.add("ffec84");
        colors.add("000000");
        colors.add("0000ff");
        colors.add("00ff00");
        colorsAdapter=new CircleColorsAdapter(colors);
        rcColor.setLayoutManager(new LinearLayoutManager(ActivityPopuSet.this,RecyclerView.HORIZONTAL,false));
        rcColor.setAdapter(colorsAdapter);
        colorsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (color==0){
                    //字体颜色
                    tvText.setTextColor(Color.parseColor("#"+colors.get(position)));
                    SPUtils.setSharedIntData(ActivityPopuSet.this,"PopuTextColor",Color.parseColor("#"+colors.get(position)));
                }else {
                    rlMid.setBackgroundColor(Color.parseColor("#"+colors.get(position)));
                    SPUtils.setSharedIntData(ActivityPopuSet.this,"PopuBgColor",Color.parseColor("#"+colors.get(position)));
                }
            }
        });

        tvTextColor.setOnClickListener(this::onClick);
        tvBackColor.setOnClickListener(this::onClick);
        tvStart.setOnClickListener(this::onClick);
        sbLocationLine.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked){
                    sbLocationLine.setChecked(true);
                }else {
                    sbLocationLine.setChecked(false);
                }
            }
        });
        sbSize.setOnSeekBarChangeListener(seekBarChangeListener);
        sbVideoSpeed.setOnSeekBarChangeListener(seekBarChangeListener);
        sbTransparent.setOnSeekBarChangeListener(seekBarChangeListener);
        myHandler=new MyHandler(ActivityPopuSet.this);

        if (SPUtils.getSharedIntData(ActivityPopuSet.this,"PopuTextColor")!=0){
            tvText.setTextColor(SPUtils.getSharedIntData(ActivityPopuSet.this,"PopuTextColor"));
        }
        if (SPUtils.getSharedIntData(ActivityPopuSet.this,"PopuBgColor")!=0){
            rlMid.setBackgroundColor(SPUtils.getSharedIntData(ActivityPopuSet.this,"PopuBgColor"));
        }

        if (SPUtils.getSharedIntData(ActivityPopuSet.this,"PopuTextSize")!=0){
            sbSize.setProgress(SPUtils.getSharedIntData(ActivityPopuSet.this,"PopuTextSize"));
            tvSize.setText(SPUtils.getSharedIntData(ActivityPopuSet.this,"PopuTextSize")+"");
        }

        if (SPUtils.getSharedIntData(ActivityPopuSet.this,"PopuTextSpeed")!=0){
            sbVideoSpeed.setProgress(SPUtils.getSharedIntData(ActivityPopuSet.this,"PopuTextSpeed"));
            tvSpeed.setText(SPUtils.getSharedIntData(ActivityPopuSet.this,"PopuTextSpeed")+"");
        }

        if (SPUtils.getSharedFloatData(ActivityPopuSet.this,"PopuTextTransparent")!=0){
            sbTransparent.setProgress(SPUtils.getSharedFloatData(ActivityPopuSet.this,"PopuTextTransparent").intValue());
            tvTransparent.setText(SPUtils.getSharedFloatData(ActivityPopuSet.this,"PopuTextTransparent")+"");
            rlMid.setAlpha((100-SPUtils.getSharedFloatData(ActivityPopuSet.this,"PopuTextTransparent"))/100);
        }
    }

    SeekBar.OnSeekBarChangeListener seekBarChangeListener=new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            switch (seekBar.getId()){
                case R.id.sbSize:
                    //字体大小设置
                    tvSize.setText((progress<15?15:progress)+"");
                    tvText.setTextSize(progress<15?15:progress);
                    break;
                case R.id.sbVideoSpeed:
                    tvSpeed.setText(progress+"");
                    break;
                case R.id.sbTransparent:
                    tvTransparent.setText(progress+"");
                    float p=Float.parseFloat(progress+"");
                    rlMid.setAlpha((100-p)/100);
                    break;
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) { }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            switch (seekBar.getId()){
                case R.id.sbSize:
                    SPUtils.setSharedIntData(ActivityPopuSet.this,"PopuTextSize",seekBar.getProgress());
                    break;
                case R.id.sbVideoSpeed:
                    SPUtils.setSharedIntData(ActivityPopuSet.this,"PopuTextSpeed",seekBar.getProgress());
                    break;
                case R.id.sbTransparent:
                    SPUtils.setSharedFloatData(ActivityPopuSet.this,"PopuTextTransparent",Float.parseFloat(seekBar.getProgress()+""));
                    break;
            }
        }
    };

    @Override
    protected void initData() { }
    /**
     * 获取要使用的标题栏样式(此函数由子类重写)
     * @return
     */
    @Override
    protected int getTitleBarType() {
        return 0;
    }

    /*
     * 创建一个计时的线程，利用handler发送计时的消息
     */

    private void startCountTime() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                for (int i = 3; i > 0; i--) {
                    Message mes = myHandler.obtainMessage();
                    mes.arg1 = i;
                    mes.what = 0x00;//计时中的标志
                    myHandler.sendMessage(mes);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Message mes = myHandler.obtainMessage();
                mes.what = 0x11;//计时完成的标志
                myHandler.sendMessage(mes);

            }
        }.start();
    }

    /**
     * 自定义一个带有MainActivity弱引用的静态Handler
     * 防止内存泄漏
     */
    private  class MyHandler extends Handler {
        WeakReference<ActivityPopuSet> wr;

        public MyHandler(ActivityPopuSet activity) {
            //实例化弱引用
            wr = new WeakReference<ActivityPopuSet>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ActivityPopuSet activity = wr.get();
            if (activity != null) {//判断该activity是否已经销毁
                switch (msg.what) {
                    case 0x00:
                        tvCountDown.setText(msg.arg1+"");
                        break;
                    case 0x11:
                        tvCountDown.setVisibility(View.GONE);
                        openFloatingWindows();
                        finish();
                        break;
                }
            }
        }
    }

    public void openFloatingWindows(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(ActivityPopuSet.this)) {
            if (mOpenPermission == null) {
                mOpenPermission = new AlertDialog.Builder(ActivityPopuSet.this).setTitle("提示").setMessage("请前往设置中心打开浮窗权限！")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mOpenPermission.dismiss();
                            }
                        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @RequiresApi(api = Build.VERSION_CODES.M)
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), REQUEST_CODES);
                                mOpenPermission.dismiss();

                            }
                        }).create();
            }
            if (!mOpenPermission.isShowing()) {
                mOpenPermission.show();
            }
        } else {
            WindowsManagerPicker.newInstances(ActivityPopuSet.this).createFloatingWindows();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode ==RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODES:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(ActivityPopuSet.this)) {
                        Toast.makeText(ActivityPopuSet.this, "授权失败！", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(ActivityPopuSet.this, "授权成功！", Toast.LENGTH_SHORT).show();
                        WindowsManagerPicker.newInstances(ActivityPopuSet.this).createFloatingWindows();
                    }
                    break;
            }
        }
    }
}